

package cn.shengchao.examstar.pay.utils;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.shengchao.base.constant.Constants;
import org.apache.commons.lang3.StringUtils;
import top.continew.starter.cache.redisson.util.RedisUtils;

import java.time.Duration;
import java.time.LocalDateTime;

public class OrderNumberUtils {
    public static String generatorOrderNumber() {
        LocalDateTime now = LocalDateTime.now();//获取当前时间
        String YYMMDD = StringUtils.substring(DateUtil.format(now, DatePattern.PURE_DATE_PATTERN), 2);
        String seconds = now.getHour() * 3600 + now.getMinute() * 60 + now.getSecond() + "";
        String secondsFMT = StringUtils.leftPad(seconds, 5, "0");
        String orderNoPrefix = YYMMDD + secondsFMT;
        String redisKeyPrefix = Constants.RedisKey.ORDER_NUMBER_KEY + Constants.COLON + orderNoPrefix;
        RedisUtils.incr(redisKeyPrefix);
        Long increment = RedisUtils.incr(redisKeyPrefix);
        if (increment == 1) {
            //每一秒的第一个订单号，设置一下key过期时间
            RedisUtils.expire(redisKeyPrefix, Duration.ofMinutes(1));
        }
        return orderNoPrefix + StringUtils.leftPad(String.valueOf(increment), 4, "0");
    }

}